package com.admin.utils;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class ExcelUtil {

    public static void download(HttpServletRequest request, HttpServletResponse response, Workbook excel, String fileName) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        excel.write(outStream);
        fileName = processFileName(request, fileName);
        byte[] content = outStream.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/x-excel");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];

            int bytesRead;
            while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException var15) {
            throw var15;
        } finally {
            if (bis != null) {
                bis.close();
            }

            if (bos != null) {
                bos.close();
            }

        }

    }

    private static String processFileName(HttpServletRequest request, String fileName) {
        String codedfilename = null;

        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {
                String name = URLEncoder.encode(fileName, "UTF8");
                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                codedfilename = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return codedfilename;
    }
}
